<template>
  <q-page class="q-pa-md">
    <!-- 查询表单 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section>
        <div class="text-h6">岗位查询</div>
      </q-card-section>
      <q-card-section>
        <q-form @submit="handleSearch" class="row q-col-gutter-md">
          <q-input
            v-model="searchForm.postName"
            label="岗位名称"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-input
            v-model="searchForm.postCode"
            label="岗位编码"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.status"
            label="状态"
            :options="statusOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <div class="col-md-12 flex justify-end">
            <q-btn type="submit" color="primary" label="查询" class="q-mr-sm" />
            <q-btn @click="resetSearch" label="重置" outline color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>

    <!-- 操作按钮和表格 -->
    <q-card flat bordered>
      <q-card-section class="row items-center">
        <div class="text-h6 col">岗位列表</div>
        <div class="col-auto q-gutter-sm">
          <q-btn color="primary" label="新增岗位" icon="add" @click="showAddDialog" />
          <q-btn
            color="negative"
            label="批量删除"
            icon="delete"
            :disable="selected.length === 0"
            @click="confirmBatchDelete"
          />
          <q-btn color="grey" label="导出" icon="download" @click="exportData" />
        </div>
      </q-card-section>

      <!-- 数据表格 -->
      <q-table
        v-model:selected="selected"
        :rows="posts"
        :columns="columns"
        row-key="postId"
        :loading="loading"
        :pagination="pagination"
        @request="onRequest"
        selection="multiple"
        binary-state-sort
        flat
        bordered
      >
        <!-- 状态列自定义 -->
        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.status"
              checked-icon="check"
              unchecked-icon="clear"
              :true-value="1"
              :false-value="0"
              color="green"
              @update:model-value="toggleStatus(props.row)"
            />
          </q-td>
        </template>

        <!-- 操作列 -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props" class="q-gutter-x-sm">
            <q-btn dense color="primary" icon="edit" @click="showEditDialog(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row.postId)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑岗位' : '新增岗位' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <q-input
              v-model="postForm.postName"
              label="岗位名称"
              :rules="[(val) => !!val || '岗位名称不能为空']"
              outlined
            />
            <q-input
              v-model="postForm.postCode"
              label="岗位编码"
              :rules="[(val) => !!val || '岗位编码不能为空']"
              outlined
            />
            <q-input
              v-model="postForm.postSort"
              label="显示排序"
              type="number"
              :rules="[(val) => val >= 0 || '排序必须大于等于0']"
              outlined
            />
            <q-select
              v-model="postForm.status"
              label="状态"
              :options="statusOptions"
              outlined
              emit-value
              map-options
            />
            <q-input v-model="postForm.remark" label="备注" type="textarea" outlined autogrow />
            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'select', label: '选择', field: '', align: 'center' },
  { name: 'postId', label: '岗位ID', field: 'postId', align: 'center', sortable: true },
  { name: 'postName', label: '岗位名称', field: 'postName', align: 'center', sortable: true },
  { name: 'postCode', label: '岗位编码', field: 'postCode', align: 'center' },
  { name: 'postSort', label: '排序', field: 'postSort', align: 'center', sortable: true },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center', sortable: true },
  { name: 'actions', label: '操作', align: 'center' },
]

// 状态选项
const statusOptions = [
  { label: '全部', value: null },
  { label: '启用', value: 1 },
  { label: '停用', value: 0 },
]

// 数据状态
const posts = ref([])
const selected = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const searchForm = ref({
  postName: '',
  postCode: '',
  status: null,
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const postForm = ref({
  postId: null,
  postName: '',
  postCode: '',
  postSort: 0,
  status: 1,
  remark: '',
})

// 初始化加载数据
onMounted(() => {
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
})

// 表格请求方法
function onRequest(props) {
  const { page, rowsPerPage } = props.pagination
  loading.value = true

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      postId: (page - 1) * rowsPerPage + i + 1,
      postName: [
        '董事长',
        '总经理',
        '部门经理',
        '项目经理',
        '开发工程师',
        '测试工程师',
        'UI设计师',
        '产品经理',
      ][i % 8],
      postCode: ['ceo', 'manager', 'dept', 'pm', 'dev', 'test', 'ui', 'product'][i % 8],
      postSort: i + 1,
      status: Math.random() > 0.3 ? 1 : 0,
      createTime: new Date().toLocaleString(),
      remark: [
        '公司最高管理者',
        '公司日常管理者',
        '部门负责人',
        '项目负责人',
        '软件开发人员',
        '软件测试人员',
        '界面设计师',
        '产品设计人员',
      ][i % 8],
    }))

    posts.value = mockData
    pagination.value.rowsNumber = 50 // 模拟总条数
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    loading.value = false
  }, 500)
}

// 查询处理
function handleSearch() {
  pagination.value.page = 1
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 重置查询
function resetSearch() {
  searchForm.value = {
    postName: '',
    postCode: '',
    status: null,
  }
  handleSearch()
}

// 显示新增对话框
function showAddDialog() {
  isEdit.value = false
  postForm.value = {
    postId: null,
    postName: '',
    postCode: '',
    postSort: 0,
    status: 1,
    remark: '',
  }
  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  postForm.value = {
    ...row,
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '岗位信息已更新' : '岗位创建成功',
  })
  dialogVisible.value = false
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 切换状态
function toggleStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === 0 ? '启用' : '停用'}岗位 ${row.postName}  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `岗位已${row.status === 0 ? '启用' : '停用'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
    })
}

// 确认删除
function confirmDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该岗位吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '岗位已删除',
    })
    onRequest({
      pagination: pagination.value,
      filter: searchForm.value,
    })
  })
}

// 批量删除
function confirmBatchDelete() {
  if (selected.value.length === 0) return

  $q.dialog({
    title: '确认批量删除',
    message: `确定要删除选中的 ${selected.value.length}  个岗位吗？此操作不可恢复！`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '已删除选中的岗位',
    })
    selected.value = []
    onRequest({
      pagination: pagination.value,
      filter: searchForm.value,
    })
  })
}

// 导出数据
function exportData() {
  $q.notify({
    type: 'positive',
    message: '导出成功',
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}
</style>
